package datasource;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * DataSource class, used to send UDP Packets with messages to the Station on a
 * specified port and interval
 * 
 */
public class DataSource {

    public static void main(String[] args) {

        if (args.length != 3) {
            System.out
                    .println("Usage: java datasource.DataSource <message> <target port> <sleep interval>");
            return;
        }
        
        System.out.println("DataSource is sending \"" + args[0] + "\" on Port " + args[1] + "..." + " [Sleep interval: " + args[2] + "]");
        
        byte[] data = new byte[24];
        try {
            DatagramSocket udpSocketSource = new DatagramSocket();
            for (int i = 0; i < 24 && i < args[0].length(); i++) {
                data[i] = args[0].getBytes()[i];
            }
            DatagramPacket uspPacket = new DatagramPacket(data, data.length,
                    InetAddress.getByName("localhost"),
                    Integer.parseInt(args[1]));

            while (true) {
                udpSocketSource.send(uspPacket);
                Thread.sleep(Integer.parseInt(args[2]));
            }

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
